using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System.Security.Claims;
using GroupSix.Application.Services;
using GroupSix.Application.Dtos;

namespace GroupSix.Api.Attributes;

/// <summary>
/// 权限验证特性
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class RequirePermissionAttribute : Attribute, IAsyncAuthorizationFilter
{
    private readonly string _permissionKey;
    private readonly string _description;

    public RequirePermissionAttribute(string permissionKey, string description = "")
    {
        _permissionKey = permissionKey;
        _description = description;
    }

    public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        // 检查用户是否已认证
        if (!context.HttpContext.User.Identity?.IsAuthenticated == true)
        {
            context.Result = new UnauthorizedResult();
            return;
        }

        // 获取用户ID
        var userIdClaim = context.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier);
        if (userIdClaim == null || !Guid.TryParse(userIdClaim.Value, out var userId))
        {
            context.Result = new UnauthorizedResult();
            return;
        }

        // 检查是否为管理员（管理员拥有所有权限）
        var roleClaim = context.HttpContext.User.FindFirst(ClaimTypes.Role);
        if (roleClaim?.Value == "admin")
        {
            return; // 管理员直接通过
        }

        // 获取权限服务
        var permissionService = context.HttpContext.RequestServices.GetService<PermissionService>();
        if (permissionService == null)
        {
            context.Result = new StatusCodeResult(500);
            return;
        }

        // 验证权限
        var request = new ValidatePermissionRequestDto
        {
            UserId = userId,
            PermissionKey = _permissionKey,
            MenuPath = context.HttpContext.Request.Path.Value
        };

        var (success, message, data) = await permissionService.ValidatePermissionAsync(request);
        
        if (!success || data?.HasPermission != true)
        {
            context.Result = new ForbidResult();
            return;
        }
    }
}

/// <summary>
/// 管理员权限特性
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class RequireAdminAttribute : Attribute, IAsyncAuthorizationFilter
{
    public Task OnAuthorizationAsync(AuthorizationFilterContext context)
    {
        // 检查用户是否已认证
        if (!context.HttpContext.User.Identity?.IsAuthenticated == true)
        {
            context.Result = new UnauthorizedResult();
            return Task.CompletedTask;
        }

        // 检查是否为管理员
        var roleClaim = context.HttpContext.User.FindFirst(ClaimTypes.Role);
        if (roleClaim?.Value != "admin")
        {
            context.Result = new ForbidResult();
            return Task.CompletedTask;
        }

        return Task.CompletedTask;
    }
} 